import React, { useEffect, useState } from 'react';
import {
 Table, Modal, Form, Input, Select, Col, InputNumber, Icon, message, Upload, Button,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  fetchShopList,
  deleteShop,
  saveStoreShop,
} from '@/services/rentCenter/basicSet';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils'

const { Option } = Select;
const { Dragger } = Upload;
const { TextArea } = Input;
const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))

const types = ['', '待确认', '空置', '使用中', '已预订', '确认失败']
const statusList = [
  {
    label: '待确认',
    id: '1',
  },
  {
    label: '空置',
    id: '2',
  },
  {
    label: '使用中',
    id: '3',
  },
  // {
  //     label: "已预订",
  //     value: "4"
  // },
  // {
  //     label: "审核失败",
  //     value: "5"
  // }
]
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: '购物中心',
    key: 'shopCenter',
  },
  {
    title: '商铺号',
    key: 'shopNumber',
  },
  {
    title: '楼栋',
    key: 'building',
  },
  {
    title: '楼层',
    key: 'floor',
  },
  {
    title: '建筑面积（㎡）',
    key: 'constructionArea',
  },
  {
    title: '计租面积（㎡）',
    key: 'rentingArea',
  },
  {
    title: '租金单价（元）',
    key: 'rentUnitPrice',
  },
  {
    title: '物业费单价（元）',
    key: 'propertyUnitPrice',
  },
  {
    title: '状态',
    key: 'status',
    render: params => (
      <span>{types[params.status]}</span>
    ),
  },
  {
    title: '备注',
    key: 'remark',
  },
  // {
  //   title: '状态',
  //   dataIndex: 'status',
  //   key: 'status',
  //   render: text => (
  //     <span>
  //       {text == 0 ? '启用' : '锁定'}
  //     </span>
  //   ),
  // },
  // {
  //   title: '创建时间',
  //   dataIndex: 'createTime',
  //   key: 'createTime',
  // },
];
const user = localStorage.getItem('user')
let users = {}
let token = ''
if (user) {
  users = JSON.parse(user)
  token = users.token
}
let downLoading = false

const uploadprops = {
  name: 'file',
  multiple: true,
  accept: '.xlsx,.xls',
  headers: {
    token: token,
  },
  action: '/Amaidan-Merchants-Web/merchants/busStoreShop/batchInsertStoreShop',
  onChange(info) {
    const { status } = info.file;
    if (status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (status === 'done') {
      message.success(`${info.file.name} file uploaded successfully.`);
    } else if (status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
}

const storeShopList = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
    condition: '',
    status: '',
  });
  const [info, setInfo] = useState({});
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);
  // 批量导入模态框
  const [showUpload, setUpload] = useState(false);

  // 列表
  const getList = async params => {
    const r = await fetchShopList(params);
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
  };
  useEffect(() => {
    getList(listQuery);
  }, []);

  // 新增修改
  // const handleRole = async params => {
  //   const r = await saveOrUpdateRole(params);
  //   if (r.code === 0) getList(listQuery);
  // };

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };

  const removeRole = async record => {
    deleteShop({
      id: record.id,
    }).then(res => {
      if (res.data.code === '0') {
        const index = data.findIndex(e => e.id === record.id);
        setColData(() => {
          data.splice(index, 1);
          return [...data];
        });
      }
    })
  };

  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        saveStoreShop(values).then(() => {
          getList(listQuery)
          setState(!isShow);
        })
      }
    });
  };

  // 查询表单
  const getFields = () => (
      <>
        <Col span={8}>
          <Form.Item label="模糊条件">
            <Input onChange={v => { setListQuery({ ...listQuery, condition: v.target.value }) }} value={listQuery.condition} placeholder="楼栋，楼层，商铺号" />
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="状态">
            <Select value={listQuery.status} placeholder="选择状态" onChange={v => { setListQuery({ ...listQuery, status: v }) }}>
              {statusList.map(r => <Option key={r.id}>{r.label}</Option>)}
            </Select>
          </Form.Item>
        </Col>
      </>
    );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 清空查询条件
  const handleReset = () => {
    setListQuery({
      pageNo: 1,
      pageSize: 10,
    })
    getList({
      pageNo: 1,
      pageSize: 10,
    })
  };

  const downLoad = () => {
    if (!downLoading) {
      downLoading = true
      document.getElementById('exportTemplate').submit()
      setTimeout(() => {
        downLoading = false
      }, 2000)
    }
  };
  const upload = () => {
    setUpload(true)
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1 && type !== 95 && type !== 94) return message.warning('请勾选一条数据！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      case 3:
        return handleStatus(record[0]);
      // 查询
      case 2:
        return handleSearch();
      // 删除
      case 4:
        return removeRole(record[0]);
      // 模板下载
      case 94:
        return downLoad();
      // 批量导入
      case 95:
        return upload();
      default:
        return ''
    }
  };

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <form id="exportTemplate" action="/Amaidan-Merchants-Web/merchants/busStoreShop/getExcelTemplate" method="post">
        <input type="hidden" name="token" value={token} />
      </form>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : data} rowSelection={rowSelection} rowKey={record => record.id} />
      <Modal
        title="批量导入"
        visible={showUpload}
        footer={[
          <Button key="back" onClick={() => { setUpload(false) }}>
            关闭
          </Button>,
        ]}
        onCancel={() => { setUpload(false) }}
        destroyOnClose
      >
        <Dragger {...uploadprops}>
          <p className="ant-upload-drag-icon">
            <Icon type="inbox" />
          </p>
          <p className="ant-upload-text">点击按钮或拖拽文件到此处上传</p>
        </Dragger>
      </Modal>
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="购物中心">
            {getFieldDecorator('shopCenter', {
              initialValue: info.shopCenter || '',
              rules: [
                {
                  required: true,
                  message: '请输入购物中心名称',
                },
              ],
            })(<Input placeholder="请输入购物中心名称" />)}
          </Form.Item>
          <Form.Item label="商铺号">
            {getFieldDecorator('shopNumber', {
              initialValue: info.shopNumber || '',
              rules: [
                {
                  required: true,
                  message: '请输入商铺号',
                },
              ],
            })(<Input placeholder="请输入商铺号" />)}
          </Form.Item>
          <Form.Item label="楼栋">
            {getFieldDecorator('building', {
              initialValue: info.building || '',
              rules: [
                {
                  required: true,
                  message: '请输入楼栋',
                },
              ],
            })(<Input placeholder="请输入楼栋" />)}
          </Form.Item>
          <Form.Item label="楼层">
            {getFieldDecorator('floor', {
              initialValue: info.floor || '',
              rules: [
                {
                  required: true,
                  message: '请输入楼层',
                },
              ],
            })(<Input placeholder="请输入楼层" />)}
          </Form.Item>
          <Form.Item label="建筑面积（㎡）">
            {getFieldDecorator('constructionArea', {
              initialValue: info.constructionArea || 0,
              rules: [
                {
                  required: true,
                  message: '请输入商铺建筑面积',
                },
              ],
            })(<InputNumber min={0} placeholder="请输入商铺建筑面积" />)}
          </Form.Item>
          <Form.Item label="计租面积（㎡）">
            {getFieldDecorator('rentingArea', {
              initialValue: info.rentingArea || 0,
              rules: [
                {
                  required: true,
                  message: '请输入商铺计租面积',
                },
              ],
            })(<InputNumber min={0} placeholder="请输入商铺计租面积" />)}
          </Form.Item>
          <Form.Item label="租金单价（元）">
            {getFieldDecorator('rentUnitPrice', {
              initialValue: info.rentUnitPrice || 0,
              rules: [
                {
                  required: true,
                  message: '请输入商铺租金单价',
                },
              ],
            })(<InputNumber min={0} placeholder="请输入商铺租金单价" />)}
          </Form.Item>
          <Form.Item label="物业费单价（元）">
            {getFieldDecorator('propertyUnitPrice', {
              initialValue: info.propertyUnitPrice || 0,
              rules: [
                {
                  required: true,
                  message: '请输入商铺物业费单价',
                },
              ],
            })(<InputNumber min={0} placeholder="请输入商铺物业费单价" />)}
          </Form.Item>
          <Form.Item label="备注">
            {getFieldDecorator('remark', {
              initialValue: info.remark || '',
            })(<TextArea />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(storeShopList));
